/**
 * @ author: 汪孟苹
 */
define(["jquery","bbcare","oms_config/root","fu/app/comm/comm",
	"scprit/followup/app/question/question.servers.js"],function($,$bb,$root,$comm,$questionServers){
	var servers = {};
	/**
	 * 获取url地址,当前用户
	 */
	var URL = $bb.baseUrl("followup");
	var sessinonUserName = JSON.parse($bb.getSessionStorage("account")).alias;
	/**
	 * 根据前一个页面传递过来的参数(患者id、实例id、任务id[可无，看情况])，获取患者信息
	 */
	var getParams = function(data,params){
		params.followQueueId = data.QueueSchemeInfo.queueId;
		params.queuename = data.QueueSchemeInfo.queueName;
		params.patientName = data.PatientInfo.userName;
		params.gender = data.PatientInfo.gender;
		var imgSrc = params.gender == 'F' ? "girl" : "boy";
		params.imgSrc = "page/followup/imgs/comm/"+ imgSrc +".png";
		params.birthday = data.PatientInfo.birthday;
		params.expectedDay = data.PatientInfo.expectedDay;
		params.pregnancyDay = data.PatientInfo.pregnancyDay;
	}
	servers.getPageParams = function(){	// 目前只需要传患者id和患者实例id
		var params = $bb.getPageParams();
		this.getRevisedInfoParams(params,null,getParams);
		return params;
	}
	/**
	 * 根据患者id和患者实例id，获取患者患者信息(队列名称、队列id、患者名称、性别)
	 */
	servers.getRevisedInfoParams = function(params,curInfo,callback){
		$bb.ajax({
			url: URL + "followup/service/patient/patientInfoQueryByPtId",
			data:JSON.stringify({
				data : {
					"patientId": params.patientId,
					"ptSchemeId": params.patientSchemeId,
				}
			}),
			success: function(data){

				if(data.success){
					callback(data.data,params,curInfo);
				}else{
					$bb.toastShow(data.msg ? data.msg : "查询患者信息出错！");
				}
			}
		});
	}
	/**
	 * 处理打印时，问卷数据
	 */
	var printQuestData = function(list){
		var arr = [];
		for (var i = 0; i < list.length; i++) {
			if(list[i].children){
				var obj = {};
				obj.children = printQuestData(list[i].children);
				if(obj.children.length > 0){
					if(list[i].label) obj.label = list[i].label;
					if(list[i].type) obj.type = list[i].type;
					arr.push(obj);
				}
			}else{
				if(list[i].id && list[i].val && list[i].label){
					var obj = {};
					obj.id = list[i].id;
					obj.label = list[i].label;
					obj.type = list[i].type;
					if(jQuery.isArray(list[i].val)){
						var str = '';
						for (var j = 0; j < list[i].val.length; j++) {
							if(obj.type == "question_multiSelect"){
								for (var j = 0; j < list[i].list.length; j++) {
									str += list[i].list[j].val + list[i].list[j].subunit;
								}
							}else{
								if(str == ""){
									str += list[i].val[j]
								}else{
									str += "、" + list[i].val[j]
								}
							}
						}
						obj.val = str;
					}else{
						obj.val = list[i].val;
					}
					arr.push(obj);
				}
			}
		}
		return arr;
	}
	/**
	 * 处理打印时，问卷数据
	 */
	servers.handlePrintQuest = function(data){
		if(data.questiones && data.values){	// 配置了问卷的情况
			var arr = $questionServers.getQuestionData({
				list: data.questiones,	  // 问卷
            	values: data.values,	// 问卷答案
			}).questions;
			var arrPrint = [];
			for (var i = 0; i < arr.length; i++) {
				arrPrint.push(printQuestData(arr[i]));
			}
			return arrPrint;
		}
	}
	/**
	 * 处理打印时，需要的患随访指导信息
	 */
	servers.handlePrintTask = function(task){
		var data = {};
		for(var key in task){
			if( key == "nextAddress"){
				data[key] = task[key][0];
			}else if(key == "finishDate" || key == "nextDateTime" || key == "finishTime"){
				data[key] = task[key];
			}
		}
		return data;
	}
	/**
	 * 处理打印时，需要的患者信息
	 */
	servers.handlePatientInfo = function(data){
		var info = {}
		info.patientName = data.PatientInfo.userName;
		info.gender = data.PatientInfo.gender == 'F' ? '女':'男';
		info.ageMonDayStr = data.ageMonDayStr;
		info.pregnancyWeekStr = data.pregnancyWeekStr;
		return info;
	}
	/**
	 * 获取打印时，需要的患者信息
	 */
	servers.getPatientInfoByPtId = function(params,params2,callback){
		$bb.ajax({
			url: URL + "followup/service/patient/patientInfoPtId",
			data:JSON.stringify({
				data : {
					"patientId": params.patientId
				}
			}),
			success: function(data){
				if(data.success){
					callback(data.data,params2);
				}else{
					$bb.toastShow(data.msg ? data.msg : "查询患者信息出错！");
				}
			}
		});
	}
	/**
	 * 获取打印时需要的医院信息（医院名字、科室名字）
	 */
	servers.handlePrintHospital = function(info,quest,callback){
		$bb.ajax({
			url: URL + "followup/service/patientFollow/queryHospitalInfo",
			success: function(data){
				if(data.success){
					callback(data.data,info,quest);
				}else{
					$bb.toastShow(data.msg ? data.msg : "查询医院信息出错！");
				}
			}
		});
	}
	/**
	 * 获取删除患者时的参数
	 */
	servers.getDeleteParams = function(){
		var params = $bb.getPageParams();
		var deleteParams = {
			oprInfo:{
				opCode: "1017",
		        opNote: "【"+sessinonUserName + "】医生将【"+params.patientName+"】患者从"+params.queuename+"中删除",
		        opType: "2",
			},
		    patientInfo:{
		    	followQueueId: params.followQueueId,
		        patientId: params.patientId,
		        ptSchemeId: params.patientSchemeId,
		    },
		};
		return deleteParams;
	}
	/**
	 * 获取请求任务列表时的参数
	 */
	var getTasksParams = function(){
		var params = $bb.getPageParams();
		return {
			"patientSchemeId": params.patientSchemeId,
			"followQueueId":params.followQueueId
		};
	}
	/**
	 * 获取当前任务的索引号（根据当前任务id和任务列表数据）
	 */
	servers.getTaskIndexByTaskId = function(rows,taskId){
		for (var i = 0; i < rows.length; i++) {
			if(rows[i].taskId == taskId){
				var index = i;
				break;
			}
		}
		return index;
	}
	/**
	 * 获取随访任务状态中是否有还未进行的任务（目的：若没有，则添加“添加随访”按钮）
	 */
	servers.getAddTaskInfo = function(rows){
		var addTaskFlag = true;
		var afterTaskId = rows[rows.length-1].taskId;
		for (var i = 0; i < rows.length; i++) {
			if(rows[i].taskStatus == "0"){
				addTaskFlag = false;
				break;
			}
		}
		return {"addTaskFlag":addTaskFlag,"afterTaskId":afterTaskId};
	}
	/**
	 * 获取保存问卷时，所需的参数
	 */
	var getSaveParams = function(data,params){
		var defaults = {
		 	ptContentIds: data.task.ptContentIds,
		 	ptTaskId: data.task.ptTaskId,
		 	ptTaskName: data.task.ptTaskName,
		 	seqNo: data.task.seqNo
		};
		var domId = $("#followUpInfo form").attr("id");
    	var questiones = $questionServers.getDataForDom(domId);
    	var task = $.extend(defaults, getDataTask("followUpInfo"));
    	var sampleList = getDataSampleList("followUpInfo");
    	var params = {
			oprInfo:{
				followQueueId: data.oprInfo.followQueueId,
				opCode:"1001",
				opNote:"【"+sessinonUserName + "】医生为【"+params.patientName+"】患者进行"+ data.task.ptTaskName +"修改",
				opType:"2",
				patientId: data.oprInfo.patientId,
				ptSchemeId: data.oprInfo.ptSchemeId,
			},
			questiones: questiones,
			task: task
		}
		var config = $root.init();
		if(config.dom.outPatientCollect){
			params = $.extend(params,{sampleList:sampleList});
		}
		return params;
	}
	/**
	 * 处理[任务列表]数据
	 */
	servers.handleTasks = function(list,taskId){
		var arr = [];
		for(var i=0;i<list.length;i++){
			arr[i] = list[i];
			if(i>0) arr[i].preTaskId = arr[i-1].taskId;
			if(taskId){
				arr[i].currentTaskFlag = false;
				if(arr[i].taskId == taskId){
					arr[i].currentTaskFlag = true;
				}
			}
			arr[i].taskDate = list[i].taskDate;		// 将年份保留
		}
		return arr;
	};
	/**
	 * 请求任务列表
	 */
	servers.ajaxTasks = function(callback,params){
		$bb.ajax({
			url: URL + "followup/service/patient/patientTaskListQuery",
			data:JSON.stringify({
				data : getTasksParams()
			}),
			success: function(data){
				if(data.success){
					callback(data.data.rows,params);
				}else{
					$bb.toastShow(data.msg ? data.msg : "随访任务列表加载失败！");
				}
			}
		});
	};
	/**
	 * 请求问卷
	 */
	servers.ajaxQuestion = function(params,curInfo,callback,addTaskInfo){
		$bb.ajax({
			url: URL + "followup/service/patient/patientTaskContentDataQuery",
			data:JSON.stringify({
				data : {
					followQueueId:params.followQueueId,
					ptTaskId:curInfo.taskId
				}
			}),
			success: function(data){
				if(data.success){console.log(callback(data.data,params,curInfo,addTaskInfo))
					callback(data.data,params,curInfo,addTaskInfo)

				}else{
					$bb.toastShow(data.msg ? data.msg : "随访问卷加载失败！");
				}
			}
		});
	};
	/**
	 * 添加随访
	 */
	servers.ajaxAddTask = function(data){
		var params = data.params;
		var callback = data.fun;
		var getTasksCallback = data.getTasksCallback;
		$bb.ajax({
			url: URL + "followup/service/patient/addTempTask",
			data:JSON.stringify({
				data : {
					"oprInfo":{
						"opCode":"1018",
				        "opNote":"【"+sessinonUserName + "】医生给【"+ params.patientName +"】患者新增了临时随访任务",
				        "opType":"2",
					},
				    "taskInfo":{
				    	"followQueueId":params.followQueueId,
				        "patientId":params.patientId,
				        "ptSchemeId":params.patientSchemeId,
				        "ptTaskId":data.afterTaskId
				    }
				}
			}),
			success: function(data){
				if(data.success){
					$bb.toastShow("添加临时随访任务成功！");
					params.taskId = data.data.newTaskId;
					callback(getTasksCallback,params);
				}else{
					$bb.toastShow(data.msg ? data.msg : "添加临时随访任务失败！");
				}
			}
		});
	};
	/**
	 * [问卷]提交
	 */
	servers.ajaxSaveQuestion = function(data1,params,curInfo,callback){
		$bb.ajax({
			url:URL + "followup/service/patient/patientTaskContentDataModify",
			data:JSON.stringify({
				data: getSaveParams(data1,params)
			}),
			success: function(data){
				if(data.success){
					callback(params,curInfo);
				}else{
					$bb.toastShow(data.msg ? data.msg : "保存失败！",3000);
				}
			}
		});
	};
	/**
	 * 删除患者
	 */
	servers.ajaxDelPatient = function(params){
		$bb.ajax({
			url: URL + "followup/service/patient/history/patientDel",
			data:JSON.stringify({
				data : params
			}),
			success: function(data){
				if(data.success){
					var config = $root.init();
					$bb.toastShow("删除成功！",2000,$bb.openPage,config.route.outPatientDelPatient);
				}else{
					$bb.toastShow(data.msg ? data.msg : "删除失败！");
				}
			}
		});
	}

	/**
	 *	获取任务状态（根据任务状态码）
	 */
	var curTaskStatus = function(status){
		if(status=="0"){
			status = "default";
		}else if(status=="1"){
			status = "readonly";
		}else if(status=="2"){
			status = "disabled";
		}
		return status;
	}
	servers.curTaskStatus = function(status){
		return curTaskStatus(status);
	}
	/**
	 * 获取当前任务信息
	 */
	servers.getCurInfo = function(rows,taskId){
		var str = "";		// 当前的任务id
		var status = "";	// 当前的任务status
		var seqNo = "";		// 当前的任务seqNo
		var preTaskId = "";		// 上一次的任务seqNo
		var taskStatus = "";	// 当前的任务taskStatus(打印问卷时判断是否显示打印按钮)
		for (var i = 0; i < rows.length; i++) {
			if(rows[i].currentTaskFlag == true){
				str = rows[i].taskId;
			}
		}
		if(str==""){
			str = rows[0].taskId;
		}
		if(taskId){	// 从随访记录中跳过来，带过来的 taskId
			str = taskId;
		}
		for (var i = 0; i < rows.length; i++) {
			if(rows[i].taskId == str){
				taskStatus = rows[i].taskStatus;
				status = curTaskStatus(rows[i].taskStatus);
				seqNo = rows[i].seqNo;
				if(i>0)preTaskId = rows[i-1].taskId;
			}
		}
		return {
			"taskId" : str,
			"status" : status,
			"seqNo" : seqNo,
			"preTaskId":preTaskId,
			"taskStatus":taskStatus
		};
	}
	/**
	 * [随访指导]随访年龄数据处理
	 */
	var getFollowupAge = function(params,finishDate){
		var actualDays = $comm.dateDiff(params.birthday,finishDate).days;
		var actualAge = $comm.dateDiff(params.birthday,finishDate).age;
		var age,ageLabel;
		if(params.expectedDay){
			var correctDays = $comm.dateDiff(params.expectedDay,finishDate).days;
			// 2岁内的早产儿用纠正年龄(孕周小于37周为早产儿)
			if( params.pregnancyDay < 37*7 && actualDays < 365*2 ){
				if(correctDays < 0){
                    var days = correctDays + 40*7;
                    var week = parseInt(days / 7);
					var day = parseInt(days % 7);
                    age = week + "周" + day + "天";
                    ageLabel = "纠正胎龄";
                }else{
                	var correctAge = $comm.dateDiff(params.expectedDay,finishDate).age;
                    age = correctAge;
					ageLabel = "纠正年龄";
                }
                return {
                	"age":age,
					"ageLabel":ageLabel,
					"actualAge":actualAge,
					"actualAgeLabel":"实际年龄"
                }
			}else{
				age = actualAge;
				ageLabel = "实际年龄";
			}
		}else{
			age = actualAge;
			ageLabel = "实际年龄";
		}
		return {
			"age":age,
			"ageLabel":ageLabel
		};
	}
	servers.getFollowupAge = function(params,finishDate){
		return getFollowupAge(params,finishDate);
	}
	/**
	 * [随访指导]数据处理
	 */
	var taskData = function(task,ageRelate,status){
		var data = $.extend({}, task);
		// data.nextTime为处理后的下次随访时间
		var config = $root.init();
		data.nextTime = config.dom.outPatientNextTimeValue ? data.nextDate[0] : data.nextDateTime;
		for(var key in data){
			if(key=="finishDate" && status == "default"){
				if( !data[key] ){
					if(data.taskStatus == "0"){
						data[key] = $comm.getCurTime().date;
					}else if(data.taskStatus == "2"){
						data[key] = data.taskDate;
					}
				}
			}else if(key=="updateAuname" && status == "default"){
				data[key] = sessinonUserName;
			}
		}
		if(data.finishDate != null){ // 有随访时间就有随访年龄
			var ageObj = getFollowupAge(ageRelate,data.finishDate);
			data.followupAge = ageObj.age;
			data.followupAgeLabel = ageObj.ageLabel;
			if(ageObj.actualAge && ageObj.actualAgeLabel){
				data.followupActualAge = ageObj.actualAge;
				data.followupActualAgeLabel = ageObj.actualAgeLabel;
			}
		}else{
			data.followupAgeLabel = "实际年龄";
		}
		if(data.followupActualAge && data.followupActualAgeLabel){
			data.length = 3;
		}else{
			data.length = 4;
		}
		return data;
	}
	/**
	 * 安医大采集数据处理
	 */
	var samplesData = function(sampleList,status){
		var arr = [];
		if(sampleList && jQuery.isArray(sampleList)) {
			var labelArr1 = ["尿液","血液","唾液","头发"];
			var labelArr2 = ["第1次","第2次","第3次"];
			var nameArr1 = ["urine","blood","saliva","hair"];
			var nameArr2 = ["1","2","3"];
			var list = [
				{
					key:"0",
					value:"未采集"
				},
				{
					key:"1",
					value:"已采集"
				}
			];
			for (var i = 0; i < sampleList.length; i++) {
				for (var j = 0; j < 3; j++) {
					var obj = {};
					obj.status = status;
					obj.sampleType = sampleList[i].sampleType;
					obj.label = labelArr1[i] + labelArr2[j];
					obj.name = nameArr1[i] + nameArr2[j];
					obj.val = j == 0 ? sampleList[i].sampleValue1 : j == 1 ? sampleList[i].sampleValue2 : sampleList[i].sampleValue3;
					if(obj.val == "") obj.val = "0";
					obj.list = list;
					arr.push(obj);
				}
			}
		}
		var config = $root.init();
		var data = {
			sampleList: arr,
			flag: config.dom.outPatientCollect
		}
		return data;
	}
	/**
	 * 问卷里若有题型里有followupGuidance字段，则写死的“随访指导”不显示,返回false；若没有，则显示返回true。
	 */
	var getFlagTaskGuide = function(list){
		for (var i = 0; i < list.length; i++) {
			if( list[i].followupGuidance ){
				return false;
			}
			if( list[i].children ){
				getFlagTaskGuide( list[i].children );
			}
		}
		return true;
	}
	/**
	 * 随访问卷task数据处理
	 */
	servers.handleFollowupTask = function(options){
		var defaults = {
			status:"default",
			showIcon: false
		};
		var opts = $.extend(defaults, options);
		var task = $.extend(defaults, taskData(opts.task,opts.ageRelate,opts.status));
		var flag = (opts.list && jQuery.isArray(opts.list)) ? true : false;
		var sampleList = samplesData(opts.sampleList,opts.status);
		var flagTaskGuide;
		for (var i = 0; i < options.list.length; i++) {
			flagTaskGuide = getFlagTaskGuide(options.list[i]);
			if(!flagTaskGuide) break;
		}
		var config = $root.init();
		flagTaskGuide = flagTaskGuide && config.dom.outPatientTaskGuide;
		var data = {
			status:task.status,
			flagQuestions:flag,		// 是否配置了问卷
			task: task,		// 随访备注
			sampleList: sampleList,	// 安医大采集
			flagTaskGuide: flagTaskGuide // 随访指导展示与否
		};
		return data;
	}
	/**
	 * 随访问卷提交时，获取task数据
	 */
	var getDataTask = function(domId){	// domId:整个问卷加随访备注的外裹domId
		var data = {};
		data.finishDate = $("#"+ domId +" input[name='finishDate']").val();
		data.nextDate = $("#"+ domId +" input[name='nextDate']").val();
		data.nextAddress = $("#"+ domId +" select[name='nextAddress']").val();
		data.updateAuname = $("#"+ domId +" p[name='updateAuname']").text();
		data.followupAge = $("#"+ domId +" p[name='followupAge']").text();
		data.taskNote = $("#"+ domId +" textarea[name='taskNote']").val();
		return data;
	}
	/**
	 * 随访问卷提交时，获取sampleList数据
	 */
	var getDataSampleList = function(domId){	// domId:整个问卷的外裹domId
		var arr = [];
		var nameArr1 = ["urine","blood","saliva","hair"];
		var nameArr2 = ["1","2","3"];
		var typeArr = ["0","1","2","3"];
		for (var i = 0; i < nameArr1.length; i++) {
			var obj = {};
			obj.sampleCode = "bioSample";
			obj.sampleType = typeArr[i];
			obj.sampleValue1 = "";
			obj.sampleValue2 = "";
			obj.sampleValue3 = "";
			for (var j = 0; j < nameArr2.length; j++) {
				var name = nameArr1[i] + nameArr2[j];
				var value = $("#"+ domId +" select[name='"+ name +"']").val();
				if(j == 0) obj.sampleValue1 = value;
				if(j == 1) obj.sampleValue2 = value;
				if(j == 2) obj.sampleValue3 = value;
			}
			arr.push(obj);
		}
		return arr;
	}
	/**
	 * 处理btnGroup数据
	 */
	servers.handleBtnGroup = function(params,params0){
		var config = $root.init();
		$.extend(params,{"showAddTaskBtn":config.dom.outPatientAddTaskBtn});
		var topbars = [];
		if( params.status == "default" ){
			var obj = {
				"icon":"fa fa-floppy-o",
				"name":"保存记录",
				"callback":params0.callback2,
				"params":params0.params2
			};
			topbars.push(obj);
		}else if( params.status == "readonly" || params.status == "disabled" ){
			var obj = {
				"icon":"fa fa-pencil-square-o",
				"name":"修改记录",
				"callback":params0.callback3,
				"params":params0.params3
			};
			topbars.push(obj);
		}
		if( params.addTaskFlag ){
			if( params.showAddTaskBtn ){
				var obj = {
					"icon":"fa fa-plus-square-o",
					"name":"临时随访",
					"callback":params0.callback4,
					"params":params0.params4
				};
				topbars.push(obj);
			}
		}
		if( params.seqNo != 0 ){
			if( params.taskStatus=="1" || params.taskStatus=="2" ){
				var obj = {
					"icon":"fa fa-print",
					"name":"打印",
					"callback":params0.callback5
				};
				topbars.push(obj);
			}
		}
		topbars.push({
			"icon":"fa fa-trash-o",
			"name":"删除患者",
			"callback":params0.callback1,
			"params":params0.params1
		});
		return topbars;
	}

	/**
	 * 获取对应锚点的id
	 */
	var handle = function(arr,newArr){
		for (var i = 0; i < arr.length; i++) {
			if( arr[i].type == "qusetion_groupCollapse" || arr[i].type == "qusetion_group" || arr[i].type == "qusetion_groupTable" ){
				newArr.push(arr[i]);
			}
		}
		return newArr;
	}

	/**
	 * 获取锚点nav的数据
	 */
	servers.handleAnchorMenu = function(list){
		var newArr = [];
		for (var i = 0; i < list.length; i++) {
			handle(list[i],newArr);
		}
		return newArr;
	}

	return servers;
});
